const User = require('../models/user');
const Student = require('../models/student');
const Teacher = require('../models/teacher');
const RefreshToken = require('../models/refreshToken');
const jwtUtils = require('../utils/jwtUtils');
const passwordUtils = require('../utils/passwordUtils');
const validationUtils = require('../utils/validationUtils');

class AuthService {
  /**
   * 用户登录
   * @param {string} username - 用户名
   * @param {string} password - 密码
   * @returns {Promise<Object>} - 登录结果，包含令牌和用户信息
   */
  static async login(username, password) {
    try {
      // 查找用户
      const user = await User.findOne({ username });
      if (!user) {
        throw new Error('用户名或密码错误');
      }

      // 检查用户状态
      if (user.status !== 'active') {
        throw new Error('用户账户已被禁用或暂停');
      }

      // 验证密码
      const isPasswordValid = await user.comparePassword(password);
      if (!isPasswordValid) {
        throw new Error('用户名或密码错误');
      }

      // 获取用户详细信息
      let userDetails = null;
      if (user.role === 'student') {
        userDetails = await Student.findOne({ userId: user._id }).populate('classId dormitoryId');
      } else if (user.role === 'teacher') {
        userDetails = await Teacher.findOne({ userId: user._id });
      }

      // 生成令牌
      const payload = {
        userId: user._id,
        username: user.username,
        role: user.role,
        name: user.name
      };
      
      const accessToken = jwtUtils.generateAccessToken(payload);
      const refreshToken = await jwtUtils.generateRefreshToken(user._id);

      return {
        success: true,
        user: {
          id: user._id,
          username: user.username,
          name: user.name,
          role: user.role,
          email: user.email,
          phone: user.phone,
          details: userDetails
        },
        tokens: {
          accessToken,
          refreshToken: refreshToken.token,
          expiresIn: 3600 // 1小时
        }
      };
    } catch (error) {
      throw error;
    }
  }

  /**
   * 用户注册
   * @param {Object} userData - 用户注册数据
   * @returns {Promise<Object>} - 注册结果
   */
  static async register(userData) {
    try {
      // 验证数据
      const usernameValidation = validationUtils.validateUsername(userData.username);
      if (!usernameValidation.isValid) {
        throw new Error(usernameValidation.message);
      }

      const passwordValidation = validationUtils.validatePasswordStrength(userData.password);
      if (!passwordValidation.isValid) {
        throw new Error(passwordValidation.message);
      }

      if (userData.email && !validationUtils.isValidEmail(userData.email)) {
        throw new Error('电子邮件格式无效');
      }

      if (userData.phone && !validationUtils.isValidPhone(userData.phone)) {
        throw new Error('手机号码格式无效');
      }

      // 检查用户名是否已存在
      const existingUser = await User.findOne({ username: userData.username });
      if (existingUser) {
        throw new Error('用户名已存在');
      }

      // 创建用户
      const user = new User({
        username: userData.username,
        password: userData.password,
        name: userData.name,
        email: userData.email,
        phone: userData.phone,
        role: userData.role || 'student'
      });

      await user.save();

      // 如果是学生或教师，创建对应的详细信息
      if (user.role === 'student' && userData.studentData) {
        const student = new Student({
          studentId: userData.studentData.studentId,
          name: user.name,
          gender: userData.studentData.gender,
          phone: user.phone,
          email: user.email,
          userId: user._id
        });
        await student.save();
      } else if (user.role === 'teacher' && userData.teacherData) {
        const teacher = new Teacher({
          name: user.name,
          email: user.email,
          phone: user.phone,
          role: userData.teacherData.role || 'lecturer',
          userId: user._id
        });
        await teacher.save();
      }

      return {
        success: true,
        message: '注册成功',
        userId: user._id
      };
    } catch (error) {
      throw error;
    }
  }

  /**
   * 刷新访问令牌
   * @param {string} refreshToken - 刷新令牌
   * @returns {Promise<Object>} - 新的访问令牌
   */
  static async refreshToken(refreshToken) {
    try {
      // 验证刷新令牌
      const tokenData = await jwtUtils.verifyRefreshToken(refreshToken);
      if (!tokenData) {
        throw new Error('无效或过期的刷新令牌');
      }

      // 获取用户信息
      const user = await User.findById(tokenData.userId);
      if (!user || user.status !== 'active') {
        throw new Error('用户不存在或已被禁用');
      }

      // 生成新的访问令牌
      const payload = {
        userId: user._id,
        username: user.username,
        role: user.role,
        name: user.name
      };
      
      const accessToken = jwtUtils.generateAccessToken(payload);

      return {
        success: true,
        accessToken,
        expiresIn: 3600 // 1小时
      };
    } catch (error) {
      throw error;
    }
  }

  /**
   * 用户登出
   * @param {string} refreshToken - 刷新令牌
   * @returns {Promise<Object>} - 登出结果
   */
  static async logout(refreshToken) {
    try {
      // 撤销刷新令牌
      const success = await jwtUtils.revokeRefreshToken(refreshToken);
      
      return {
        success: success,
        message: success ? '登出成功' : '令牌无效'
      };
    } catch (error) {
      throw error;
    }
  }

  /**
   * 重置密码
   * @param {string} username - 用户名
   * @param {string} newPassword - 新密码
   * @returns {Promise<Object>} - 重置结果
   */
  static async resetPassword(username, newPassword) {
    try {
      // 验证密码强度
      const passwordValidation = validationUtils.validatePasswordStrength(newPassword);
      if (!passwordValidation.isValid) {
        throw new Error(passwordValidation.message);
      }

      // 查找用户
      const user = await User.findOne({ username });
      if (!user) {
        throw new Error('用户不存在');
      }

      // 更新密码
      user.password = newPassword;
      await user.save();

      // 撤销所有刷新令牌
      await jwtUtils.revokeAllUserRefreshTokens(user._id);

      return {
        success: true,
        message: '密码重置成功'
      };
    } catch (error) {
      throw error;
    }
  }

  /**
   * 生成验证码（模拟）
   * @returns {Promise<Object>} - 验证码信息
   */
  static async generateCaptcha() {
    try {
      // 模拟生成验证码
      const captchaCode = Math.random().toString(36).substring(2, 8).toUpperCase();
      
      return {
        success: true,
        captcha: captchaCode,
        captchaImage: ''
      }
    } catch (error) {
      throw error;
    }
  }
}

module.exports = AuthService;